﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Jinshiyu.Models;

namespace Jinshiyu.Controllers
{
    [Authorize]
    public class OrderController:Controller
    {
        private JinshiyuEntities db = new JinshiyuEntities();


        public ActionResult Index()
        {
            return RedirectToAction("List");
        }



        public ViewResult Details(long id)
        {
            Order order = db.Orders.Find(id);
            return View(order);
        }


        public ActionResult Create()
        {
            ViewBag.PresentHour = DateTime.Now.Hour;
            ViewBag.Today = DateTime.Now.Date.ToLongDateString();

            #region 设置各种下拉框的SelectListItem
            var ColorList = new List<SelectListItem>();
            ColorList.Add(new SelectListItem
            {
                Text = "黑色",
                Value = "黑色"
            });
            ColorList.Add(new SelectListItem
            {
                Text = "银灰",
                Value = "银灰"
            });

            ViewData["color"] = ColorList;


            var typeList = new List<SelectListItem>();
            foreach (var price in db.Prices)
            {
                typeList.Add(new SelectListItem
                {
                    Text = price.价格名称,
                    Value = price.价格名称 + "|" + price.价格1.ToString()
                });
            }
            ViewData["typelist"] = typeList;
            #endregion


            var order = new OrderViewModel();

            try
            {
                var cMember = db.CMembers.Single(c => c.账户 == User.Identity.Name);
                order.账户 = cMember.账户;
                order.车牌号 = cMember.车牌号;
                order.车型 = cMember.车型;
                order.颜色 = cMember.颜色;
                if (DateTime.Now.Hour > 16)
                {
                    order.预约时间1 = DateTime.Now.Date.AddDays(1);
                    ViewBag.StartHour = 6;
                }
                else
                {
                    order.预约时间1 = DateTime.Now.Date;
                    ViewBag.StartHour = DateTime.Now.Hour + 1;
                }
                order.Address = cMember.地址;
                order.地图级数 = cMember.地图级数 ?? 11;
                order.Latitude = cMember.纬度 ?? decimal.Parse("39.924219");
                order.Longitude = cMember.经度 ?? decimal.Parse("116.399803");
            }
            catch (Exception e)
            {
                throw e;
            }

            return View(order);
        }


        [HttpPost]
        public ActionResult Create(Order order)
        {
            C会员 cMember;

            try
            {
                cMember = db.CMembers.Single(c => c.账户 == User.Identity.Name);
            }
            catch (Exception e)
            { throw e; }

            //添加、更新订单表、会员表、常用汽车表、常用地址表
            UpdateCMember(order, cMember);
            AddUsualCar(order, cMember);
            AddUsualAddress(order, cMember);

            //C会员账户余额由数据库触发器“订单插入”计算，因此在此处不要更新账户余额字段
            if (cMember.账户余额 == null || cMember.账户余额 < order.金额)
            {
                return RedirectToAction("PayOrder", "Alipay", order);
            }

            #region 查询是否有网店记录
            /*先将订单记录插入数据库中，存储过程将计算洗车地点是否处于服务区内,
             * 如果是，则自动分配网店；
             * 如果不是，则删除当前记录。*/
            try
            {
                db.Orders.Add(order);
                db.SaveChanges();
            }
            catch (Exception e) { }
            finally
            {
                db.Dispose();
                db = new JinshiyuEntities();
                order = db.Orders.Find(order.订单编号);
            }
            if (order == null)
            {
                return View("ClubFail");
            }
            #endregion

            order.已完成 = false;
            order.C会员编号 = cMember.C会员编号;
            order.账户 = cMember.账户;
            order.下单时间 = DateTime.Now;
            db.Orders.Add(order);

            db.SaveChanges();
            return RedirectToAction("Success", "Order");
        }


        #region Create订单时调用的全部方法

        private void UpdateCMember(Order order, C会员 cMember)
        {
            if (ModelState.IsValid)
            {
                cMember.车牌号 = order.车牌号;
                cMember.车型 = order.车型;
                cMember.颜色 = order.颜色;
                cMember.地址 = order.Address;
                cMember.电话 = order.电话;
                cMember.经度 = order.Longitude;
                cMember.纬度 = order.Latitude;
                cMember.地图级数 = order.地图级数;
                cMember.手机 = order.手机;
            }
        }

        private void AddUsualCar(Order order, C会员 cMember)
        {
            var usualCar = new 常用车牌();

            usualCar.车牌号 = order.车牌号;
            usualCar.车型 = order.车型;
            usualCar.会员编号 = cMember.C会员编号;
            usualCar.颜色 = order.颜色;
            db.常用车牌.Add(usualCar);
        }

        private void AddUsualAddress(Order order, C会员 cMember)
        {
            var usualAddress = new FrequentlyUsedAddresses();

            //usualAddress.城市 = 
            //usualAddress.区 = 
            usualAddress.地图级数 = order.地图级数;
            usualAddress.地址 = order.Address;
            usualAddress.会员编号 = cMember.C会员编号;
            usualAddress.经度 = order.Longitude;
            usualAddress.纬度 = order.Latitude;
            db.FrequentlyUsedAddresses.Add(usualAddress);
        }
        #endregion

        /// <summary>
        /// 支付宝支付成功后，更新此订单的完成状态
        /// </summary>
        /// <param name="orderID">订单编号</param>
        private void OrderComplete(string orderID)
        {
            var order = db.Orders.Find(long.Parse(orderID));
            order.已完成 = true;

        }


        public ActionResult Edit(long id)
        {
            Order order = db.Orders.Find(id);
            return View(order);
        }


        [HttpPost]
        public ActionResult Edit(Order order)
        {
            if (ModelState.IsValid)
            {
                db.Entry(order).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(order);
        }


        public ActionResult Delete(long id)
        {
            Order order = db.Orders.Find(id);
            return View(order);
        }


        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(long id)
        {
            Order order = db.Orders.Find(id);
            db.Orders.Remove(order);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        public ActionResult ListCompleted(OrderListViewModel orderList)
        {
            ViewBag.Action = "ListCompleted";

            var orders = db.Orders.Where(o => o.账户 == User.Identity.Name && o.已完成 == true).OrderByDescending(o => o.下单时间);

            var order = DoIndex(orders, orderList);

            if (Request.IsAjaxRequest())
            {
                return PartialView("OrdersGrid", order);
            }
            else
            {
                return View("List", order);
            }
        }

        public ActionResult ListUncompleted(OrderListViewModel orderList)
        {
            ViewBag.Action = "ListUncompleted";

            var orders = db.Orders.Where(o => o.账户 == User.Identity.Name && o.已完成 == false).OrderByDescending(o => o.下单时间);

            var order = DoIndex(orders, orderList);

            if (Request.IsAjaxRequest())
            {
                return PartialView("OrdersGrid", order);
            }
            else
            {
                return View("List", order);
            }
        }

        private OrderListViewModel DoIndex(IQueryable<Order> orders, OrderListViewModel orderList)
        {
            orderList.PagerViewModel.TotalItems = orders.Count();

            var order = new OrderViewModel();

            orderList.ListOfOrders = orders
                .Skip(orderList.PagerViewModel.Skip)
                .Take(orderList.PagerViewModel.Take);

            //        foreach (var o in orders
            //.Skip(orderList.PagerViewModel.Skip)
            //.Take(orderList.PagerViewModel.Take))
            //        {
            //            order.Address = o.Address;
            //            order.Latitude = o.Latitude ?? 0;
            //            order.Longitude = o.Longitude ?? 0;
            //            order.Scratch = o.Scratch;
            //            order.车牌号 = o.车牌号;
            //            order.车型 = o.车型;
            //            order.订单编号 = o.订单编号;
            //            order.发票 = o.发票;
            //            order.结束时 = o.结束时 ?? 6;
            //            order.金额 = o.金额;
            //            order.起始时 = o.起始时 ?? 6;
            //            order.洗车类型 = o.洗车类型;
            //            order.颜色 = o.颜色;
            //            order.预约时间1 = o.预约时间1;
            //        };

            return orderList;
        }


        public ActionResult Success()
        {
            return View();
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }

    }
}
